//$URL: http://dasding.googlecode.com/svn/trunk/api/src/main/java/de/piratech/dasding/security/contextfilter/UsernameCheckContextFilter.java $
//$Id: UsernameCheckContextFilter.java 88 2012-11-05 22:54:19Z amuthmann@gmail.com $
package de.piratech.dasding.security.contextfilter;

import javax.ws.rs.ext.Provider;



import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import de.piratech.dasding.data.User;
import de.piratech.dasding.security.UserSecurityContext;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Filter that checks if the accessing user has the same name as the requested path.
 *
 * @author deveth0
 *
 */
@Provider    // register as jersey's provider
public class UsernameCheckContextFilter implements ResourceFilter, ContainerRequestFilter {

  private final static Logger LOG = LoggerFactory.getLogger(UsernameCheckContextFilter.class);
  private final UriInfo mUriInfo;

  public UsernameCheckContextFilter(UriInfo pUriInfo) {
    this.mUriInfo = pUriInfo;
  }

  @Override
  public ContainerRequest filter(ContainerRequest pRequest) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object principle = authentication == null ? null : authentication.getPrincipal();
    if (principle != null && principle instanceof User) {
      String requestId = mUriInfo.getPathParameters().get("userid").get(0);
      User user = (User) principle;
      if (StringUtils.equals(user.getName(), requestId)) {
        pRequest.setSecurityContext(new UserSecurityContext(user));
        return pRequest;
      } else {
        LOG.info("User {} has requested another users ({}) path.", user.getName(), requestId);
        throw new WebApplicationException(Response.Status.FORBIDDEN);
      }
    }
    LOG.info("Failed userid check");
    throw new WebApplicationException(Response.Status.UNAUTHORIZED);
  }

  @Override
  public ContainerRequestFilter getRequestFilter() {
    return this;
  }

  @Override
  public ContainerResponseFilter getResponseFilter() {
    return null;
  }
}